<template>
    <v-md-editor 
        ref="vmdEditorRef"
        :modelValue="modelValue"
        @update:modelValue="doChange"
        @change="contentChange"
        left-toolbar="undo redo clear | h bold italic strikethrough quote | ul ol table hr | link image code | emoji| todo-list | save"
        :disabled-menus="[]" @upload-image="handleUploadImage" :include-level="[1, 2, 3, 4, 5, 6]" class="md-editor">
    </v-md-editor>
</template>

<script setup>
import { ref, reactive } from 'vue'
import axios from 'axios'
import useUserStore from '@/store/user'
const userStore = useUserStore()

const props = defineProps({
    modelValue: {
        type: String,
        default:''
    },
    type: { // 上传文件是用来做什么的, 比如是文章的图片
        type:String,
        default:'article'
    }
})

const emits = defineEmits(['update:modelValue'])

const vmdEditorRef = ref(null)
function focus() {
    vmdEditorRef.value.focus()
}
defineExpose({
    focus
})

function doChange(content) {
    emits('update:modelValue',content)
}
function contentChange(text, html) {
    emits('contentChange',{text,html})
}

// 处理上传文件
function handleUploadImage(event, insertImage, files) {
    // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
    console.log(files);

    let formData = new FormData()
    formData.append('mfile',files[0])
    formData.append('type',props.type)
    formData.append('json',props.jsonStr)

    console.log(formData);
    axios({
        url:'http://119.23.61.24/api/file/uploadFile',
        data: formData,
        method:'post',
        headers: {
            Authorization: userStore.token
        }
    }).then(res=>{
        console.log(res,'pic');
        // 此处只做示例
        insertImage({
            url:`http://119.23.61.24/api/static${res.data.data}`,
            desc: files[0].name,
            // width: 'auto',
            // height: 'auto',
        });
    })

}
</script>

<style lang="scss" scoped>
.md-editor {
    height: 100% !important;
}

.v-md-editor {
    height: 100% !important;
}
</style>